﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TimeTracker.Data.Contracts;
using TimeTracker.Model;

namespace TimeTracker.Data
{
    public class TimeTrackerUow : ITimeTrackerUow, IDisposable
    {
        protected IRepositoryProvider RepositoryProvider { get; set; }
        private TimeTrackerDbContext DbContext { get; set; }

        public TimeTrackerUow(IRepositoryProvider repositoryProvider)
        {
            CreateDbContext();
            repositoryProvider.DbContext = DbContext;
            RepositoryProvider = repositoryProvider;
        }

        public IActivitiesRepository Activities { get { return GetRepo<IActivitiesRepository>(); } }
        public IRepository<ActivityBundle> ActivityBundles { get { return GetStandardRepo<ActivityBundle>(); } }
        public IRepository<CompetenceLevel> CompetenceLevels { get { return GetStandardRepo<CompetenceLevel>(); } }
        public IRepository<EffectivenessGrade> Grades { get { return GetStandardRepo<EffectivenessGrade>(); } }
        public IRepository<Task> Tasks { get { return GetStandardRepo<Task>(); } }
        public ITimeRepository Time { get { return GetRepo<ITimeRepository>(); } }

        public void Commit()
        {
            DbContext.SaveChanges();
        }

        protected void CreateDbContext()
        {
            DbContext = new TimeTrackerDbContext();
            DbContext.Configuration.ProxyCreationEnabled = false;
            DbContext.Configuration.LazyLoadingEnabled = false;
            DbContext.Configuration.ValidateOnSaveEnabled = false;
        }

        private IRepository<T> GetStandardRepo<T>() where T : class
        {
            return RepositoryProvider.GetRepositoryForEntityType<T>();
        }

        private T GetRepo<T>() where T : class
        {
            return RepositoryProvider.GetRepository<T>();
        }

        #region IDisposable

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (DbContext != null)
                {
                    DbContext.Dispose();
                }
            }
        }
        #endregion
    }
}
